//
//  OrderListViewController.m
//  CreditHub
//
//  Created by chenglang on 2024/9/14.
//

#import "OrderListViewController.h"
#import "OrderTableViewCell.h"
#import "OrderService.h"
#import "WebViewController.h"
#import "UUID.h"

@interface OrderListViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *arrOrder;
@property (nonatomic, strong) UIView *bgView;
@end

@implementation OrderListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.mas_equalTo(0);
    }];
//    [self.tableView.mj_header beginRefreshing];


}

- (void)viewWillAppear:(BOOL)animated{
    [self requestOrderList];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.arrOrder.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 210;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    OrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderTableViewCell" forIndexPath:indexPath];
    cell.dicInfo = self.arrOrder[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dicInfo = self.arrOrder[indexPath.row];
    NSString *faint = CHString(dicInfo[@"generous"]);
    if ([faint length] >= 4) {
        NSString *substring = [faint substringToIndex:4];
        if ([substring isEqualToString:@"http"]) {
            WebViewController *webView = [[WebViewController alloc] init];
            webView.url = [self getRequestUrlString:faint] ;
            [self.navigationController pushViewController:webView animated:YES];
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:faint] options:@{} completionHandler:^(BOOL success) {
                
            }];
        }
    }
}
- (NSString *)getRequestUrlString:(NSString *)str {
    
    NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    
    NSString *url= [NSString stringWithFormat:@"%@&areal=%@&boo=%@&howling=%@&ear=%@&knew=%@&minute=%@&which=1",str,[UserInfoModel getUserInfo].areal,appVersion,[BaseService friendlyDeviceName],[UUID getUUID],[[UIDevice currentDevice] systemVersion],[BaseService getIDFA]];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
    return url;
}
- (UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"OrderTableViewCell" bundle:nil] forCellReuseIdentifier:@"OrderTableViewCell"];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
//        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerLoadMore)];
        
        MJRefreshNormalHeader *header = (MJRefreshNormalHeader *)_tableView.mj_header;
        [header setValue:@(YES) forKeyPath:@"stateLabel.hidden"];
        [header setValue:@(YES) forKeyPath:@"lastUpdatedTimeLabel.hidden"];
        
        MJRefreshAutoNormalFooter *footer = (MJRefreshAutoNormalFooter *)_tableView.mj_footer;
        [footer setValue:@(YES) forKeyPath:@"stateLabel.hidden"];
        
    }
    return  _tableView;
}
- (void)headerRefresh {

    [self requestOrderList];
}
//- (void)footerLoadMore {
//    
//    [self requestOrderList];
//}

- (void)requestOrderList{
    
    __weak typeof(self) weakSelf = self;
    [OrderService requestOrderList:[NSString stringWithFormat:@"%@",@(self.type)] success:^(NSURLSessionDataTask *task, id response) {
        
        if([response[@"ofexcitement"] integerValue] == 0){
            NSArray *array = [NSArray arrayWithArray:response[@"pity"][@"tentacles"]];
            weakSelf.arrOrder = [NSMutableArray arrayWithArray:array];
            if(array.count == 0){
                weakSelf.tableView.backgroundView = weakSelf.bgView;
            }else{
                weakSelf.tableView.backgroundView = nil;
            }
            [weakSelf.tableView reloadData];
        }else{
            xhl_showMessage(response[@"shared"]);
        }
        
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}
- (UIView *)bgView{
    if(!_bgView){
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
      
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"order_no_data"]];
        [_bgView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(-30);
            make.centerX.mas_equalTo(0);
        }];
        
        UILabel *label = [[UILabel alloc] init];
        label.text = @"You don't have an order yet";
        label.font = [UIFont systemFontOfSize:14];
        label.textAlignment = NSTextAlignmentCenter;
        [_bgView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.top.equalTo(imageView.mas_bottom).offset(10);
        }];
    }
    return _bgView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
